import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) => MaterialApp(
        title: '第02课 - Dart 基础',
        theme: ThemeData(useMaterial3: true, colorSchemeSeed: Colors.teal),
        home: const Lesson02Page(),
      );
}

class Person {
  final String name;
  final int age;
  const Person({required this.name, this.age = 0});
  factory Person.from(Map<String, dynamic> json) => Person(
        name: json['name'] as String,
        age: (json['age'] as int?) ?? 0,
      );
}

Future<String> fetchMessage() async {
  await Future.delayed(const Duration(seconds: 1));
  return 'Hello from Future';
}

Stream<int> counterStream(int max) async* {
  for (var i = 0; i <= max; i++) {
    await Future.delayed(const Duration(milliseconds: 250));
    yield i;
  }
}

class Lesson02Page extends StatefulWidget {
  const Lesson02Page({super.key});
  @override
  State<Lesson02Page> createState() => _Lesson02PageState();
}

class _Lesson02PageState extends State<Lesson02Page> {
  String msg = '加载中...';
  int streamValue = 0;

  @override
  void initState() {
    super.initState();
    _load();
    counterStream(12).listen((v) => setState(() => streamValue = v));
  }

  Future<void> _load() async {
    final people = [
      const Person(name: 'Alice', age: 20),
      const Person(name: 'Bob', age: 25),
      Person.from({'name': 'Cathy', 'age': 18}),
    ];
    final ages = people.map((p) => p.age).toList();
    final sum = ages.fold(0, (a, b) => a + b);

    try {
      final fetched = await fetchMessage();
      setState(() => msg = '$fetched | 年龄总和: $sum');
    } catch (e) {
      setState(() => msg = '加载失败');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载失败: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dart 基础速成')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(msg, style: const TextStyle(fontSize: 18)),
            const SizedBox(height: 12),
            Text('流式计数: $streamValue'),
          ],
        ),
      ),
    );
  }
}